package com.ruoyi.message.general.service;

import com.ruoyi.message.general.properties.DxbProperties;
import com.ruoyi.message.general.util.OkHttp3Util;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;

@Service
@Slf4j
public class DxbService {

    @Autowired
    private  DxbProperties dxb;

    public boolean sendSms(String phone, String context) {
        Response response = null;
        try {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("http://api.smsbao.com/sms?")
                    .append("u=")
                    .append(dxb.getUserName())
                    .append("&p=")
                    .append(dxb.getApiKey())
                    .append("&m=")
                    .append(phone)
                    .append("&c=")
                    .append(URLEncoder.encode(context, "utf-8"));
            log.info("发送短信开始：phone:{}", phone);
            response = OkHttp3Util.send(stringBuilder.toString(), null, OkHttp3Util.GET, null);
            String result = response.body().string();
            log.info("发送短信：phone:{},result:{}", phone, result);
            return result != null && result.equals("0");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return false;
    }

    public boolean sendWSms(String phone, String context) {
        Response response = null;
        try {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("http://api.smsbao.com/wsms?")
                    .append("u=")
                    .append(dxb.getUserName())
                    .append("&p=")
                    .append(dxb.getApiKey())
                    .append("&m=")
                    .append(URLEncoder.encode("+", "utf-8"))
                    .append(phone)
                    .append("&c=")
                    .append(URLEncoder.encode(context, "utf-8"));
            log.info("发送短信开始：phone:{}", phone);
            response = OkHttp3Util.send(stringBuilder.toString(), null, OkHttp3Util.GET, null);
            String result = response.body().string();
            log.info("发送短信：phone:{},result:{}", phone, result);
            return result != null && result.equals("0");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return false;
    }
}
